import 'package:animations/animations.dart';
import 'package:bitsdojo_window/bitsdojo_window.dart';
import 'package:bnotes/constants.dart';
import 'package:bnotes/pages/archive_page.dart';
import 'package:bnotes/pages/home_page.dart';
import 'package:bnotes/pages/search_page.dart';
import 'package:bnotes/pages/settings_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:nextcloud/nextcloud.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:titled_navigation_bar/titled_navigation_bar.dart';
import 'package:universal_platform/universal_platform.dart';

enum ViewType { Tile, Grid }

class ScrawlApp extends StatefulWidget {
  const ScrawlApp({Key? key}) : super(key: key);

  @override
  _ScrawlAppState createState() => _ScrawlAppState();
}

class _ScrawlAppState extends State<ScrawlApp> {
  late SharedPreferences sharedPreferences;
  bool isTileView = false;
  ViewType viewType = ViewType.Tile;
  bool isAppLogged = false;
  String appPin = "";

  bool isAndroid = UniversalPlatform.isAndroid;
  bool isIOS = UniversalPlatform.isIOS;
  bool isWeb = UniversalPlatform.isWeb;
  bool isDesktop = UniversalPlatform.isDesktop;

  late PageController _pageController;
  int _page = 0;

  final _pageList = <Widget>[
    new HomePage(title: kAppName),
    new ArchivePage(),
    new SearchPage(),
    new SettingsPage(),
  ];

  void onPageChanged(int page) {
    setState(() {
      this._page = page;
    });
  }

  getPref() async {
    sharedPreferences = await SharedPreferences.getInstance();
    setState(() {
      isAppLogged = sharedPreferences.getBool("is_logged") ?? false;
      appPin = sharedPreferences.getString("app_pin") ?? '';
      bool isTile = sharedPreferences.getBool("is_tile") ?? false;
      print(appPin);
      viewType = isTile ? ViewType.Tile : ViewType.Grid;
    });
  }

  Future getdata() async {
    sharedPreferences = await SharedPreferences.getInstance();
    if (isAppLogged) {
      try {
        final client = NextCloudClient.withCredentials(
          Uri(host: sharedPreferences.getString('nc_host')),
          sharedPreferences.getString('nc_username') ?? '',
          sharedPreferences.getString('nc_password') ?? '',
        );
        final userData = await client.avatar.getAvatar(
            sharedPreferences.getString('nc_username').toString(), 150);
        sharedPreferences.setString('nc_avatar', userData);
      } on RequestException catch (e, stacktrace) {
        ScaffoldMessenger.of(context).showSnackBar(new SnackBar(
          content: Text('Unable to login. Try again.'),
          duration: Duration(seconds: 2),
        ));
      }
    }
  }

  void navigationTapped(int page) {
    _pageController.animateToPage(page,
        duration: const Duration(milliseconds: 300), curve: Curves.ease);
  }

  @override
  void initState() {
    super.initState();
    getPref();
    getdata();
    _pageController = new PageController();
  }

  Future<bool> onWillPop() async {
    if (_pageController.page!.round() == _pageController.initialPage) {
      sharedPreferences.setBool("is_app_unlocked", false);
      return true;
    } else {
      _pageController.jumpToPage(_pageController.initialPage);
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        systemNavigationBarIconBrightness: Brightness.light,
        systemNavigationBarColor: kSecondaryDark,
      ),
    );
    return WillPopScope(
      onWillPop: () => Future.sync(onWillPop),
      child: Scaffold(
          appBar: PreferredSize(
            preferredSize: Size(MediaQuery.of(context).size.width, 56),
            child: Visibility(
              child: AppBar(
                title: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(13),
                      child: Image.asset('images/icon.png', width: 30),
                    ),
                    SizedBox(width: 5),
                    Container(
                      alignment: Alignment.center,
                      child: Text(
                        kAppName,
                        style: TextStyle(
                          fontWeight: FontWeight.w900,
                          color: Color(0xFFC0BBE9),
                          fontSize: 23,
                          fontFamily: 'yuyang',
                        ),
                      ),
                    ),
                  ],
                ),
                actions: [
                  Visibility(
                    visible: viewType == ViewType.Tile && _page == 0,
                    child: IconButton(
                      icon: Icon(Icons.grid_view_outlined),
                      onPressed: () {
                        setState(() {
                          viewType = ViewType.Grid;
                          HomePage.staticGlobalKey.currentState!
                              .toggleView(viewType);
                        });
                      },
                    ),
                  ),
                  Visibility(
                    visible: viewType == ViewType.Grid && _page == 0,
                    child: IconButton(
                      icon: Icon(Icons.view_agenda_outlined),
                      onPressed: () {
                        setState(() {
                          viewType = ViewType.Tile;
                          HomePage.staticGlobalKey.currentState!
                              .toggleView(viewType);
                        });
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
          body: PageView(
            physics: NeverScrollableScrollPhysics(),
            pageSnapping: false,
            children: [
              new HomePage(title: kAppName),
              new SearchPage(),
              new ArchivePage(),
              new SettingsPage(),
            ],
            onPageChanged: onPageChanged,
            controller: _pageController,
          ),
          bottomNavigationBar: TitledBottomNavigationBar(
              currentIndex: _page,
              onTap: navigationTapped,
              activeColor: Color(0xFFC0BBE9),
              items: [
                TitledNavigationBarItem(
                    title: Text('错题'), icon: Icon(Icons.notes)),
                TitledNavigationBarItem(
                    title: Text('搜索'), icon: Icon(Icons.search_outlined)),
                TitledNavigationBarItem(
                    title: Text('已复习'), icon: Icon(Icons.check_circle_outline)),
                TitledNavigationBarItem(
                    title: Text('设置'), icon: Icon(Icons.settings)),
              ])),
    );
  }
}

class WindowButtons extends StatelessWidget {
  final buttonColors = WindowButtonColors(
      iconNormal: kPrimaryColor,
      mouseOver: Colors.black12,
      mouseDown: Colors.black12,
      iconMouseOver: kPrimaryColor,
      iconMouseDown: kPrimaryColor);

  final closeButtonColors = WindowButtonColors(
      mouseOver: Colors.black12,
      mouseDown: Colors.black12,
      iconNormal: kPrimaryColor,
      iconMouseOver: Colors.red,
      iconMouseDown: Colors.red);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        MinimizeWindowButton(colors: buttonColors),
        MaximizeWindowButton(colors: buttonColors),
        CloseWindowButton(colors: closeButtonColors),
      ],
    );
  }
}
